package service

import (
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/repository"
	"ruanGongKeShe16Zu/service/vo"
	"sync"

	"github.com/gin-gonic/gin"
)

// 单例实现
var InstrumentServiceInstance *InstrumentService
var InstrumentServiceOnce sync.Once

type InstrumentService struct {
	Repository repository.InstrumentRepository
}

func GetInstrumentService() *InstrumentService {
	InstrumentServiceOnce.Do(func() {
		repository := repository.NewInstrumentRepository().(repository.InstrumentRepository)
		repository.DB.AutoMigrate(&model.Instrument{})
		InstrumentServiceInstance = &InstrumentService{
			Repository: repository,
		}
	})
	return InstrumentServiceInstance
}

func (s *InstrumentService) Create(ctx *gin.Context, req *vo.InstrumentReq) (*model.Instrument, error) {
	instrumentModel := model.Instrument{
		Name:         req.Name,
		Img:          req.Img,
		Describe:     req.Describe,
		Specials:     req.Specials,
		Price:        req.Price,
		Unit:         req.Unit,
		Store:        req.Store,
		CategoryID:   req.CategoryID,
		CategoryName: req.CategoryName,
	}
	instrument, err := s.Repository.Create(&instrumentModel)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return nil, err
	}
	return instrument, nil
}

func (s *InstrumentService) Retrieve(ctx *gin.Context, id uint) (*model.Instrument, error) {
	instrument, err := s.Repository.SelectById(id)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return nil, err
	}
	return instrument, nil
}

func (s *InstrumentService) Update(ctx *gin.Context, item *model.Instrument, requestItem *vo.InstrumentReq) (*model.Instrument, error) {
	instrument, err := s.Repository.Update(*item, *requestItem)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return nil, err
	}
	return instrument, nil
}

func (s *InstrumentService) Delete(ctx *gin.Context, id uint) error {
	err := s.Repository.DeleteById(id)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return err
	}
	return nil
}

// InstrumentList 列举分类
func (s *InstrumentService) InstrumentList(ctx *gin.Context, req *vo.ListInstrumentReq) (resp *vo.DataListResp, err error) {
	instruments, err := s.Repository.InstrumentList(req)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return
	}
	Resp := make([]*vo.ListInstrumentResp, 0)
	for _, v := range instruments {
		Resp = append(Resp, &vo.ListInstrumentResp{
			ID:           v.ID,
			Name:         v.Name,
			Img:          v.Img,
			Describe:     v.Describe,
			Specials:     v.Specials,
			Price:        v.Price,
			Unit:         v.Unit,
			Store:        v.Store,
			CategoryID:   v.CategoryID,
			CategoryName: v.CategoryName,
			CreatedAt:    v.CreatedAt.String(),
		})
	}

	resp = &vo.DataListResp{
		Item:  Resp,
		Total: int64(len(Resp)),
	}

	return
}
